package edu.guet.cn.blogbasics.entity;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * @Auther: hejianding
 * @Date: 2021/4/8 9:54
 * @Version: 1.0
 */

/**
 * 工具实体类
 */
public class JwtAuthUser implements UserDetails {

    private Integer id;
    private String username;
    private String password;
    private List<String> roles;
    private Collection<? extends GrantedAuthority> authorities;

    /**
     * 通过Users来构建JwtAuthUser
     * @return
     */
    public JwtAuthUser(Users users){
        this.id= Math.toIntExact(users.getUserId());
        this.username=users.getUserName();
        this.password=users.getPassword();
        this.roles= Collections.singletonList(users.getRole());
    }

    /**
     * 鉴权过程中最重要的方法，通过该方法返回用户的权限
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new HashSet<>();
        if (roles!=null){
            for (String role: roles){
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        System.out.println("authorities:"+authorities);
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public String toString(){
        return "JwtAuthUser{"+
                "id:" +id+
                ",username='" +username+ '\''+
                ",password='" +password+ '\''+
                ",authUser='" +roles +
                '}';
    }
}
